package com.tmzn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tmzn.db.DataSource;
import com.tmzn.db.DataSourceType;
import com.tmzn.domain.TChargeRecord;
import com.tmzn.mapper.TChargeRecordMapper;
import com.tmzn.service.DeviceControlerService;
import com.tmzn.service.ITChargeRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class TChargeRecordServiceImpl extends ServiceImpl<TChargeRecordMapper, TChargeRecord> implements ITChargeRecordService {

    @Autowired
    private DeviceControlerService deviceControlerService;
    @Override
    @DataSource(DataSourceType.SLAVE)
    public void startCharge(String deviceId, String ccid, Integer userId,Integer port) {
        deviceControlerService.startCharge(deviceId,ccid,port);
        TChargeRecord tChargeRecord = new TChargeRecord();
        tChargeRecord.setCreateTime(LocalDateTime.now());
        tChargeRecord.setDeviceId(deviceId);
        tChargeRecord.setStatus(0L);
        tChargeRecord.setUserId(userId);
        this.save(tChargeRecord);
    }

    @Override
    public void endChargeNotice(String deviceId) {
        LambdaQueryWrapper<TChargeRecord> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.orderByDesc(TChargeRecord::getCreateTime);
        objectLambdaQueryWrapper.eq(TChargeRecord::getDeviceId,deviceId).eq(TChargeRecord::getStatus,0);
        objectLambdaQueryWrapper.last(" limit 1");
        TChargeRecord one = this.getOne(objectLambdaQueryWrapper);
        if(one != null){
            one.setStatus(1L);
            one.setEndTime(LocalDateTime.now());
            this.updateById(one);
        }

    }


}
